package net.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.bo.KUtilisateur;
import net.ko.framework.Ko;
import net.ko.framework.KoSession;
import net.ko.http.objects.KRequest;
import net.ko.mapping.IMappingControl;

public class LogControl implements IMappingControl {

	@Override
	public boolean isValid(HttpServletRequest request,
			HttpServletResponse response) {
		boolean result = request.getSession().getAttribute("activeUser") != null;
		if (KRequest.isPost(request)) {
			String login = KRequest.GETPOST("login", request);
			String password = KRequest.GETPOST("password", request);
			if (!result) {
				Ko.setTempConstraintDeph(2);
				KUtilisateur user = (KUtilisateur)KoSession.kloadOne(KUtilisateur.class, "login='" + login +"' AND password='"+password+"'");
				if (user.isLoaded()) {
					request.getSession().setAttribute("activeUser", user);
				}
				Ko.restoreConstraintDeph();
			}
		}
		return result;
	}

	@Override
	public void onInvalidControl(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			String message = "";
			if(KRequest.keyExists("nom", request))
				message = "&msg=Connexion impossible";
			response.sendRedirect("connexion.do?_ajx"+message);
		} catch (Exception e) {}

	}

	@Override
	public boolean beforeProcessAction(HttpServletRequest request,
			HttpServletResponse response) {
		return true;
	}

}
